package com.example.zuelweb.controller;

import com.example.zuelweb.service.PyRcongnizeService;
import com.example.zuelweb.service.FindService;
import com.example.zuelweb.util.DHashUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.io.IOException;


@RestController
public class UploadController {

    @Resource
    private FindService findService;

    @Resource
    private PyRcongnizeService pr;


    @PostMapping("/web/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {

        try {
            //需不需要上传到服务器上
            String filename = file.getOriginalFilename();
            File destFile = new File("E:\\Study\\Java\\JavaWeb_Zuel\\zuel-web\\src\\main\\resources\\static\\upload\\", filename);
            file.transferTo(destFile);

//            String imageHash = DHashUtil.getDHash(destFile);

            if (findService.redisFind(filename) != null) {
                //redis查找成功
                return findService.redisFind(filename);

            } else if (findService.mysqlFind(filename) != null) {
                //数据库查找成功
                String res = findService.mysqlFind(filename);
                //存入redis
                findService.redisAdd(filename,res);
                return res;

            } else {
                //识别图片
                String result = pr.pyrecognize(filename);
                //存入数据库（redis和mysql）
                //存入mysql
                Integer res = findService.mysqlAdd(filename,result);
                if (res==0){
                    System.out.println("数据库插入失败");
                }
                //存入redis
                findService.redisAdd(filename,result);

                return result;
            }


        } catch (IOException e) {
            e.printStackTrace();
            return "error";
        }
    }




}
